<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>表单数据管理</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <style>
        /* 遮罩层样式 */
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        /* 放大图样式 */
        .zoomed-image {
            max-width: 80%;
            max-height: 80%;
            border: 2px solid #fff;
            background-color: white;
        }

        .editor-view {
            width: 80%;
            height: 80%;
            border: 2px solid #fff;
            padding: 5px;
            overflow: auto;
            background-color: white;
        }

        /* 关闭按钮样式 */
        .close-button {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 24px;
            color: #fff;
            cursor: pointer;
        }
    </style>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">表单数据</label>
                    <div class="layui-input-inline">
                        <input type="text" name="formData" placeholder="请输入" class="layui-input" id="title">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <button class="layui-btn layui-btn-md " lay-submit lay-filter="formData-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-md" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="layui-card">
    <div class="layui-card-body">
        <table id="formData-table" lay-filter="formData-table"></table>
    </div>
</div>

<script type="text/html" id="form-toolbar">
    <button class="layui-btn layui-btn-danger layui-btn-md" lay-event="batchRemove">
        <i class="layui-icon layui-icon-delete"></i>
        删除
    </button>
</script>
<script type="text/html" id="form-bar">
    <button class="layui-btn layui-bg-blue layui-btn-sm" lay-event="view"><i
            class="layui-icon layui-icon-eye"></i>
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="remove"><i
            class="layui-icon layui-icon-delete"></i>
    </button>
</script>


<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    let baseURL = /*[[@{/}]]*/ '';


    layui.use(['table', 'form', 'jquery', 'util'], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let fieldList = JSON.parse(parent.fieldData)
        let fieldCols = fieldList.map(item => ({
            field: item.id,
            title: item.label,
            templet: function (d) {
                let id = item.id
                let f = JSON.parse(d.formData)
                if (id.includes("image_")) {
                    let v = 'image' + id
                    let images = f['imgFile'].find(i => i[v])?.[v]
                    if (images === undefined) {
                        return '无数据'
                    }
                    return images.map(path => {
                        let imagePath = path.replace(/\\/g, '/');
                        return `<img class="zoomable-image" src="${baseURL + imagePath}" alt="Image" style="width:120px; height:120px; margin:5px;">`;
                    }).join('');
                }
                if (id.includes("file_")) {
                    let v = 'file' + id
                    let files = f['files'].find(i => i[v])?.[v]
                    if (files === undefined) {
                        return '无数据'
                    }
                    return files.map(path => {
                        let filePath = path.replace(/\\/g, '/');
                        let fileName = filePath.split("/").pop().split("_").pop()
                        return `<li><a href="${baseURL + filePath}" download="${fileName}" style="margin-left: 10px; color: #1e9fff;">
                         【><span style="text-decoration: underline">${fileName}</span>】
                         </a></li>`;
                    }).join('');
                }
                if (id.includes("date_")) {
                    id = 'date' + id
                }
                if (id.includes("dateRange_")) {
                    return f['start' + id] + ' —— ' + f['end' + id]
                }
                if (id.includes("editor_")) {
                    return `<div class="editor-data">${f[id]}</div>`;
                }
                if (id.includes("checkbox_")) {
                    let dynamicParts = [];
                    let regex = new RegExp(id + "\\[(.*?)\\]");
                    for (let key in f) {
                        if (key.startsWith(id)) {
                            let match = key.match(regex);
                            if (match) {
                                dynamicParts.push(match[1]);
                            }
                        }
                    }
                    return dynamicParts ? dynamicParts : '无数据'
                }
                if (id.includes("sign_")) {
                    let v = id
                    if (f['signs'] === undefined) {
                        return '无数据'
                    }
                    let sign = f['signs'].find(i => i['id'] === v)?.['data']
                    if (sign === undefined) {
                        return '无数据'
                    }
                    return `<img class="zoomable-image" src="${sign}" alt="Image" style="width:120px; height:120px; margin:5px;border: 1px solid black">`;
                }
                return f[id] !== undefined ? f[id] : '无数据'
            }
        }));

        let cols = [
            [
                {type: 'checkbox', rowspan: 2},
                {
                    field: 'formName',
                    title: '表单名称',
                    minWidth: 150,
                    align: "center",
                    rowspan: 2,
                    templet: function () {
                        return parent.formName
                    }
                },
                {field: 'submitUser', title: '提交用户', minWidth: 120, rowspan: 2},
                {field: 'createTime', title: '创建时间', minWidth: 120, align: "center", rowspan: 2},
                {
                    field: 'formData1', title: '表单数据', minWidth: 200, align: "center", colspan: fieldCols.length
                },

                {title: '操作', templet: '#form-bar', width: 240, align: 'center', fixed: 'right', rowspan: 2}
            ]
        ]
        cols.push(fieldCols)
        table.render({
            elem: '#formData-table',
            url: baseURL + 'workflow/formData/list',
            type: 'get',
            toolbar: '#form-toolbar',
            page: true,
            limit: 10,
            limits: [10, 20, 30],
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            where: {
                formId: parent.formId
            },
            cols: cols,
            lineStyle: 'height: 95px;',
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.list,
                };
            },
            response: {
                statusCode: 1000
            },
            done: function () {
                bindZoomEvents(); // 绑定图片点击事件
            }
        });
        // 监听查询按钮，动态加载表格数据
        form.on('submit(formData-query)', function (data) {
            // 获取表单中的查询条件
            let field = data.field;

            // 重新加载表格，并传递查询参数
            table.reload('formData-table', {
                where: {
                    formId: parent.formId,
                    formData: field.formData,  // 栏目名查询条件
                },
                page: {
                    curr: 1 // 从第一页开始
                }
            });

            return false; // 阻止表单跳转
        });

        table.on('tool(formData-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'view') {
                window.view(obj);
            }
        });

        table.on('toolbar(formData-table)', function (obj) {
            if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });


        // 显示错误信息的函数
        function showErrorMessage(message) {
            layer.msg(message, {
                icon: 2,
                time: 1000
            });
        }


        //删除表单数据
        window.remove = function (obj) {
            layer.confirm("确定要删除该表单数据吗", {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + "workflow/formData/delete/" + obj.data['formDataId'],
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                table.reload('formData-table');
                            });
                        } else {
                            showErrorMessage(result.msg)
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        showErrorMessage('请求失败，请稍后再试');
                    }
                });
            });
        };

        //查看
        window.view = function (obj) {
            let data = obj.data;
            window.nowFieldData = parent.fieldData
            window.formData = data.formData
            window.nowFormName = parent.formName
            layer.open({
                type: 2,
                title: '表单数据查看',
                shade: 0.1,
                shadeClose: true,
                area: ['100%', '100%'],
                content: 'preview_data',
            })
        }
        //批量删除表单数据
        window.batchRemove = function (obj) {
            let data = table.checkStatus(obj.config.id).data;
            if (data.length === 0) {
                layer.msg("未选中数据", {icon: 3, time: 1000});
                return false;
            }
            let ids = data.map(item => item.formDataId)
            layer.confirm('确定要删除选中的数据吗？', {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + "workflow/formData/removeBatch",
                    data: {
                        formDataIds: ids
                    },
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                                table.reload('formData-table');
                            });
                        } else {
                            showErrorMessage(result.msg)
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        showErrorMessage('请求失败，请稍后再试');
                    }
                });
            });
        };

        //重置按钮
        document.getElementById('resetBtn').addEventListener('click', function () {
            table.reload('formData-table', {
                page: {curr: 1}
            });
        });


        function bindZoomEvents() {
            // 获取所有可放大的图片
            const images = document.querySelectorAll('.zoomable-image');
            images.forEach(img => {
                img.addEventListener('click', () => {
                    // 创建遮罩层
                    const overlay = document.createElement('div');
                    overlay.classList.add('overlay');

                    // 创建放大图
                    const zoomedImage = document.createElement('img');
                    zoomedImage.src = img.src;
                    zoomedImage.classList.add('zoomed-image');

                    // 创建关闭按钮
                    const closeButton = document.createElement('span');
                    closeButton.classList.add('close-button');
                    closeButton.textContent = '×';
                    closeButton.addEventListener('click', () => {
                        document.body.removeChild(overlay);
                    });

                    // 将放大图和关闭按钮添加到遮罩层
                    overlay.appendChild(zoomedImage);
                    overlay.appendChild(closeButton);

                    // 将遮罩层添加到页面中
                    document.body.appendChild(overlay);

                    // 显示遮罩层
                    overlay.style.display = 'flex';
                });
            });

            const editors = document.querySelectorAll('.editor-data');
            editors.forEach(editor => {
                editor.addEventListener('click', () => {
                    // 创建遮罩层
                    const overlay = document.createElement('div');
                    overlay.classList.add('overlay');

                    // 创建放大图
                    const zoomedImage = document.createElement('div');
                    zoomedImage.innerHTML = editor.innerHTML;
                    zoomedImage.classList.add('editor-view');

                    // 创建关闭按钮
                    const closeButton = document.createElement('span');
                    closeButton.classList.add('close-button');
                    closeButton.textContent = '×';
                    closeButton.addEventListener('click', () => {
                        document.body.removeChild(overlay);
                    });

                    // 将放大图和关闭按钮添加到遮罩层
                    overlay.appendChild(zoomedImage);
                    overlay.appendChild(closeButton);

                    // 将遮罩层添加到页面中
                    document.body.appendChild(overlay);

                    // 显示遮罩层
                    overlay.style.display = 'flex';
                });
            });
        }

    })
</script>
</body>
</html>
